<template>
  <div class="uploadImg">
    <div class="upload-item">
      <el-upload
        ref="uploadObj"
        :action="action"
        list-type="picture-card"
        multiple
        :limit="limitNum"
        name="file"
        :file-list="formData.fileList"
        :on-change="handleChange"
        :auto-upload="false"
        :accept="acceptType"
        :class="{ disabledImg: uploadDisabled }"
      >
        <!-- v-bind="$attrs" -->
        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
        <template #file="{ file }">
          <div class="fileDiv">
            <div class="fileClass">
              <template v-if="file.status == 'ready'">
                <el-image
                  class="pic_img"
                  :src="file.url"
                  :preview-src-list="[file.url]"
                  fit="contain"
                />
              </template>
            </div>
            <div class="deleteIcon">
              <el-icon @click="deleteUploadItem(file)"><CircleClose /></el-icon>
            </div>
          </div>
        </template>
      </el-upload>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, nextTick, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Plus, CircleClose } from "@element-plus/icons-vue";
import { compressPic } from "@/utils/tools";

interface formModel {
  fileList: Array<any>;
  fileOption: Array<any>;
  uid?: string;
}

const uploadObj = ref();
const formData = reactive<formModel>({
  fileList: [], // 附件回显列表
  fileOption: [], // 需要上传的附件列表
  uid: "",
});

const props = defineProps({
  // 回显的附件列表
  filesData: {
    type: Array,
    default: function () {
      return [];
    },
  },
  // 请求url
  action: {
    type: String,
    default: "#",
  },
  // 最大上传数量
  limitNum: {
    type: Number,
    default: 1,
  },
  // 文件格式
  acceptType: {
    type: String,
    default: ".jpg, .jpeg, .png",
  },
  // 是否自动上传
  autoUpload: {
    type: Boolean,
    default: false,
  },
  // 文件大小限制
  fileSize: {
    type: Number,
    default: 2048,
  },
});
const { acceptType, fileSize } = toRefs(props);

const emits = defineEmits(["updateFileList"]);

const uploadDisabled = computed(() => {
  return formData.fileOption.length;
});

// 有回显时才需要2
watch(
  () => props.filesData,
  (val) => {
    formData.fileList = [];
    if (val) {
      if (val.length > 0) {
        val.forEach((itm: any, index: number) => {
          formData.fileList.push({
            name: itm.fileName,
            url: itm.filePath,
            id: itm.id,
            status: "success",
            suffixName: itm.suffixName,
          });
        });
      }
    } else {
      formData.fileList = [];
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

// 删除上传列表
const deleteUploadItem = (file: Record<string, any>) => {
  // console.log("删除图片----", file);

  var newArr = formData.fileOption;
  newArr.forEach((item, index) => {
    if (file.uid == item.uid) {
      newArr.splice(index, 1);
    }
  });
  formData.fileOption = newArr;
  uploadObj.value.handleRemove(file);
  emits("updateFileList", formData.fileOption);
  ElMessage.success("删除成功！");
};

// 文件改变
const handleChange = async (file: any, fileList: Array<any>) => {
  // console.log("file*------*-----", file);
  // 上传校验
  let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension = acceptType.value;
  const isLt2M = file.size / 1024 < fileSize.value;
  if (!extension.includes(testmsg)) {
    ElMessage.warning(`上传文件只能是 ${acceptType.value}格式!`);
    fileList.splice(-1, 1); //移除错误文件
    return false;
  }
  if (!isLt2M) {
    let unit = fileSize.value >= 1024 ? "Mb" : "KB";
    let size =
      fileSize.value >= 1024
        ? (fileSize.value / 1024).toFixed(2)
        : fileSize.value;
    ElMessage.warning(`上传文件大小不能超过 ${size} ${unit}!`);
    fileList.splice(-1, 1);
    return false;
  }
  // 图片压缩，格式默认统一返回.jpg格式
  let newFile = await compressPic(file.raw);
  // console.log("newFile---  ", newFile);

  // const addTypeArray = newFile.raw.name.split(".");
  // const addType = addTypeArray[addTypeArray.length - 1]; // 原文件后缀
  // newFile.raw.suffixName = "." + addType;
  formData.fileOption.push(newFile);

  emits("updateFileList", formData.fileOption);
};

onMounted(() => {
  nextTick(() => {
    formData.fileOption = [];
  });
});
</script>

<style lang="scss" scoped>
.uploadImg {
  width: 100%;
}

.upload-item {
  width: 100%;
  height: 100%;

  > div {
    width: 100%;
    height: 100%;
  }

  .disabledImg {
    :deep(.el-upload--picture-card) {
      display: none;
    }
  }
}

:deep(.el-upload-list--picture-card) {
  width: 100%;
  height: 100%;
}

:deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.fileDiv {
  position: relative;
}

.fileClass {
  display: flex;
  align-items: center;
  justify-items: center;
  width: 100%;
  height: 100%;

  .pic_img {
    width: 100%;
  }
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

.deleteIcon {
  position: absolute;
  top: -3px;
  right: 0;
  cursor: pointer;
}
</style>
